<template>
  <div class="dialog">
    <el-dialog :title="title" :visible.sync="visible" :close-on-click-modal="false" :before-close="closeNetWorker"
      width="70%">
      <el-form :model="createForm" label-width="120px" label-suffix=":" :rules="rules" ref="createForm">
        <div class="page-panel-title" style="margin-top: 0">采购单信息</div>
        <div class="page-panel">
          <el-row :gutter="24">
            <el-col :span="12">
              <el-form-item label="采购单名称" prop="name">
                <el-input v-model.trim="createForm.name" placeholder="请输入采购单名称" :readonly="readonly"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="费用合计" prop="totalPrice">
                <el-input v-model.trim="createForm.totalPrice" type="number" placeholder="" readonly></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24">
            <el-col :span="12">
              <el-form-item label="备注信息" prop="conserveMemo">
                <el-input v-model.trim="createForm.conserveMemo" placeholder="请输入备注信息" :readonly="readonly"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </div>
        <div class="page-panel-title">商品明细</div>
        <div class="page-pane2" v-if="!readonly">
          <el-button size="mini" type="primary" @click="insertEvent()">新增项目</el-button>
        </div>
        <vxe-table border show-overflow resizable ref="xTable" row-id="id" height="350px" :edit-rules="validRules"
          :edit-config="{
      trigger: 'click',
      mode: 'row',
      showUpdateStatus: false,
      showInsertStatus: false,
      beforeEditMethod({ columnIndex }) {
        return !readonly
      }
    }" :data="listData">
          <vxe-column type="seq" width="60"></vxe-column>
          <vxe-column field="itemType" title="商品类型" :edit-render="{}" :filter-multiple="false">
            <template #default="{ row }">
              <span>{{
      formatterFiled(row.itemType, "dictItemCode", "dictItemName", itemTypeList)
    }}</span>
            </template>
            <template #edit="{ row }">
              <vxe-select v-model="row.itemType" transfer placeholder="商品类型">
                <vxe-option v-for="item in itemTypeList" :key="item.dictItemCode" :value="item.dictItemCode"
                  :label="item.dictItemName"></vxe-option>
              </vxe-select>
            </template>
          </vxe-column>
          <vxe-column title="操作" width="110">
            <template #default="{ row }">
              <vxe-button type="text" status="primary" v-if="!readonly" @click="selectData(row)">选择项目</vxe-button>
            </template>
          </vxe-column>
          <vxe-column field="itemName" title="名称" :edit-render="{}">
            <template #edit="{ row }">
              <vxe-input v-model="row.itemName" type="text"></vxe-input>
            </template>
          </vxe-column>
          <!-- <vxe-column field="itemModel" title="规格型号">
            <template #edit="{ row }">
              <vxe-input v-model="row.itemModel" type="text"></vxe-input>
            </template>
          </vxe-column> -->
          <vxe-column field="itemUnit" title="计量单位" width="120" :edit-render="{}">
            <template #edit="{ row }">
              <vxe-input v-model="row.itemUnit" type="text"></vxe-input>
            </template>
          </vxe-column>
          <vxe-column field="itemPrice" title="单价" width="100" :edit-render="{}">
            <template #edit="{ row }">
              <vxe-input v-model="row.itemPrice" type="float" @change="onNumberChange(row)" :digits="2"></vxe-input>
            </template>
          </vxe-column>
          <vxe-column field="itemNumber" title="数量" width="100" :edit-render="{}">
            <template #edit="{ row }">
              <vxe-input v-model="row.itemNumber" type="integer" @change="onNumberChange(row)" :digits="2"></vxe-input>
            </template>
          </vxe-column>
          <!-- <vxe-column field="laborCost" title="工时费" width="110" :edit-render="{}">
            <template #edit="{ row }">
              <vxe-input
                v-model="row.laborCost"
                type="integer"
                @change="onLaborCostChange(row)"
                :digits="2"
              ></vxe-input>
            </template>
          </vxe-column> -->
          <vxe-column field="itemTotalprice" title="总价" width="100">
            <template #edit="{ row }">
              <!-- <vxe-input
                v-model="row.itemTotalprice"
                type="float"
                :digits="2"
              ></vxe-input> -->
            </template>
          </vxe-column>
          <vxe-column field="payStatus" title="状态" width="100">
            <template #default="{ row }">
              <span>{{
      row.payStatus == "1" ? "已支付" : "未支付"
    }}</span>
            </template>
          </vxe-column>
          <vxe-column title="操作" width="100">
            <template #default="{ row }">
              <template>
                <vxe-button v-if="!readonly" type="text" status="primary" @click="removeEvent(row)">删除</vxe-button>
              </template>
            </template>
          </vxe-column>
        </vxe-table>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeNetWorker()">关 闭</el-button>
        <el-button v-if="!readonly" type="primary" @click="confirmData('createForm')">保 存</el-button>
      </div>
      <material-list-dialog ref="materialTable" @ok="getMaterialInit"></material-list-dialog>
    </el-dialog>
  </div>
</template>
<script>
import {
  storeConserveMasterQueryById,
  addConserveMaster,
  updateConserveMaster,
} from "@/api/business";
import { getDictionaryItemMap } from "@/api/common";
import SubjectListDialog from "@/components/dialog/SubjectListDialog";
import MaterialListDialog from "@/components/dialog/MaterialListDialog";
import ThemeListDialog from "@/components/dialog/ThemeListDialog";
import UserListDialog from "@/components/dialog/UserListDialog";
export default {
  name: "MaintainDialog",
  components: {
    SubjectListDialog,
    MaterialListDialog,
    ThemeListDialog,
    UserListDialog
  },
  data () {
    const numberValid = ({ cellValue }) => {
      if (cellValue && cellValue <= 0) {
        return new Error("格式不正确，必须大于0");
      }
    };
    return {
      title: "",
      visible: false,
      readonly: false,
      createForm: {
        totalPrice: 0
      },
      itemTypeList: [],
      listData: [],
      currentRow: {},
      rules: {
        name: [{ required: true, message: "请输入采购单名称", trigger: "blur" }],
      },
      validRules: {
        itemType: [{ required: true, message: "商品类型不能为空" }],
        itemName: [{ required: true, message: "名称不能为空" }],
        itemUnit: [{ required: true, message: "计量单位不能为空" }],
        itemPrice: [
          { required: true, message: "单价不能为空" },
          { validator: numberValid },
        ],
        itemNumber: [
          { required: true, message: "数量不能为空" },
          { validator: numberValid },
        ],
        // laborCost: [{ validator: numberValid }],
        // itemTotalprice: [
        //   { required: true, message: "总价不能为空" },
        //   { validator: numberValid },
        // ],
      },
    };
  },
  created () { },
  mounted () { },
  methods: {
    add () {
      // const table = this.$refs.xTable;
      // if (table) {
      //   table.remove();
      // }
      this.readonly = false;
      this.title = "新增";
      this.createForm = {};
      this.init();
      this.visible = true;
    },
    edit (val, flag) {
      // const table = this.$refs.xTable;
      // if (table) {
      //   table.remove();
      // }
      if (flag) {
        this.title = "详情";
      } else {
        this.title = "编辑";
      }
      this.readonly = flag;
      this.initEdit(val);
      this.visible = true;
    },
    initEdit (val) {
      getDictionaryItemMap({ codeArr: "itemType" }).then((res) => {
        let data = res.data;
        if (data && data.code == 0) {
          this.itemTypeList = data.data.itemType;
          storeConserveMasterQueryById({ id: val.id }).then((res) => {
            if (res.data.code == 0) {
              this.createForm = res.data.data;
              res.data.data.recordList.forEach((element) => {
                element.laborCost = 0;
                this.insertEventNoEdit(element);
              });
            }
          });
        }
      });
    },
    init () {
      getDictionaryItemMap({ codeArr: "itemType" }).then((res) => {
        let data = res.data;
        if (data && data.code == 0) {
          this.itemTypeList = data.data.itemType;
        }
      });
    },
    // 插入数据
    async insertEvent (val) {
      if (!val) {
        val = {};
      }
      const $table = this.$refs.xTable;
      const newRecord = val;
      const { row: newRow } = await $table.insertAt(newRecord, -1);
      await $table.setActiveRow(newRow);
    },
    // 插入数据最后不编辑
    async insertEventNoEdit (val) {
      if (!val) {
        val = {};
      }
      const $table = this.$refs.xTable;
      const newRecord = val;
      const { row: newRow } = await $table.insertAt(newRecord, -1);
    },
    async removeEvent (row) {
      if (row.payStatus == "1") {
        this.$message.warning("该项已付款，不能删除");
        return;
      }
      this.$confirm("确定删除该数据?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(async () => {
        const $table = this.$refs.xTable;
        if ($table) {
          $table.remove(row);
          this.countTotalPrice();
        }
      }).catch(() => { });
    },
    formatterFiled (cellValue, key, val, list) {
      let item = list.find((item) => item[key] === cellValue);
      return item ? item[val] : "";
    },
    selectData (val) {
      if (!val.itemType) {
        this.$message.warning("请先选择商品类型");
        return;
      }
      this.currentRow = val;
      if (val.itemType == "01") {
        this.$refs.materialTable.add(this.createForm.carTypeId, "0");
      } else if (val.itemType == "02") {
        this.$refs.materialTable.add(this.createForm.carTypeId, "1");
      } else if (val.itemType == "04" || val.itemType == "05") {
        this.$refs.modelForm.add(this.createForm.carTypeId);
      } else if (val.itemType == "03") {
        this.$refs.userList.add();
      }
    },
    getMaterialInit (val) {
      const $table = this.$refs.xTable;
      this.currentRow.itemId = val.id;
      this.currentRow.itemName = val.name;
      this.currentRow.itemUnit = val.unit;
      this.currentRow.supplierId = val.supplierId;
      this.currentRow.supplierName = val.supplier;
      this.currentRow.itemPrice = val.wholesaleDecimal;
      this.currentRow.itemNumber = 1;
      this.currentRow.itemTotalprice = val.wholesaleDecimal;
      this.currentRow.laborCost = 0;
      $table.reloadRow(this.currentRow);
      this.countTotalPrice();
    },
    getCoaInit (val) {
      const $table = this.$refs.xTable;
      this.currentRow.itemId = val.itemId;
      this.currentRow.itemName = val.itemName;
      this.currentRow.itemNumber = val.itemNumber;
      this.currentRow.itemPrice = val.itemPrice;
      this.currentRow.itemTotalprice = val.itemTotalprice;
      this.currentRow.itemUnit = val.itemUnit;
      this.currentRow.itemModel = val.itemModel;
      this.currentRow.laborCost = 0;
      $table.reloadRow(this.currentRow);
      this.countTotalPrice();
    },
    onNumberChange (row) {
      const $table = this.$refs.xTable;
      row.itemTotalprice =
        Number(row.itemPrice) * Number(row.itemNumber);
      $table.reloadRow(row);
      this.countTotalPrice();
    },
    onLaborCostChange (row) {
      const $table = this.$refs.xTable;
      row.itemTotalprice =
        Number(row.itemPrice) * Number(row.itemNumber);
      $table.reloadRow(row);
      this.countTotalPrice();
    },
    countTotalPrice () {
      const tableData = this.$refs.xTable.getTableData().tableData;
      let totalPrice = 0;
      tableData.forEach((element) => {
        totalPrice = totalPrice + Number(element.itemTotalprice);
      });
      this.$set(this.createForm, "totalPrice", totalPrice);
    },
    async confirmData (formData) {
      if (this.createForm.totalPrice == 0) {
        this.$confirm('该订单总价为0，确认保存?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          await this.confirmData1(formData)
        }).catch(() => {
        })
      } else {
        this.confirmData1(formData)
      }
    },
    async confirmData1 (formData) {
      const $table = this.$refs.xTable;
      const errMap = await $table.validate().catch((errMap) => errMap);
      if (errMap) {
        // this.$message.success("保存成功");
        return;
      }
      this.$refs[formData].validate((valid) => {
        if (valid) {
          const tableData = this.$refs.xTable.getTableData().tableData;
          let recordList = [];
          tableData.forEach((element) => {
            let el;
            if (element.id && element.id.includes("row")) {
              el = Object.assign(element, { id: null });
            } else {
              el = element;
            }
            recordList.push(el);
          });
          this.createForm.recordList = recordList;
          if (this.createForm.id) {
            updateConserveMaster(this.createForm).then((res) => {
              const data = res.data;
              if (data.code == 0) {
                this.$message.success("保存成功");
                this.$emit("ok");
                this.closeNetWorker();
              } else {
                this.$message.error(data.data || "保存成功");
              }
            });
          } else {
            addConserveMaster(this.createForm).then((res) => {
              const data = res.data;
              if (data.code == 0) {
                this.$message.success("新增成功");
                this.$emit("ok");
                this.closeNetWorker();
              } else {
                this.$message.error(data.data || "新增失败");
              }
            });
          }
        }
      });
    },
    closeNetWorker () {
      this.createForm = {};
      this.listData = [];
      this.readonly = false;
      this.visible = false;
    },
  },
};
</script>
<style scoped lang="less">
.content {
  height: 400px;
  overflow: auto;
}
</style>
